import React from 'react'
import "./task.less"
import {Button, DatePicker, Form, Input, message, Modal, Popconfirm, Table, Tag} from "antd";
import {addTask, completeTask, getTaskList, removeTask} from "../../api/task"
import {flushSync} from 'react-dom'

// 对日期的处理的方法
const formatTime = (time) => {
    let arr = time.match(/\d+/g),
        [, month, day, hours = '00', minutes = '00'] = arr;
    return `${month.padStart(2, 0)}-${day.padStart(2, 0)} ${hours}:${minutes}`
}

class Task extends React.PureComponent {
    state = {
        curTag: 0,// 当前标签
        listData: [],
        columns: [
            {
                title: '编号',
                dataIndex: 'id',
                align: 'center',//居中
                width: '8%'
            },
            {
                title: '任务描述',
                dataIndex: 'task',
                ellipsis: true, // 超出隐藏
                align: 'center',//剧中
                width: '50%'
            },
            {
                title: '状态',
                dataIndex: 'state',
                align: 'center',//剧中
                width: '10%',
                render: (text, record) => { // 复杂逻辑渲染
                    // text:某个单元格数据
                    return text === 2 ? '已完成' : '未完成'
                }
            },
            {
                title: '完成时间',
                dataIndex: 'time',
                align: 'center',//剧中
                width: '15%',
                render: (_, record) => {
                    let {state, time, complete} = record
                    if (+state === 2) time = complete;
                    return formatTime(time)
                }
            },
            {
                title: '操作',
                render: (_, record) => {
                    let {state, id} = record
                    return <>
                        <Popconfirm
                            title="你确定要删除这个任务?"
                            onConfirm={this.handleDelete.bind(this, id)}
                        >
                            <Button type="link">删除</Button>
                        </Popconfirm>
                        {state === 1 ? <Popconfirm
                            title="你确定要完成这个任务?"
                            onConfirm={this.handleUpdate.bind(this, id)}
                        >
                            <Button type="link">完成</Button>
                        </Popconfirm> : null}
                    </>
                }
            }
        ],
        tableLoading: false,
        modelOpen: false,
        confirmLoading: false,
        formData: {// 表单规则
            task: "",
            time: ""
        }
    }
    // 组件实例
    formRef = null;
    // 校验规则
    rules = {
        task: [{required: true, message: '任务描述是必填项'}, {min: 6, message: '输入的内容至少6位及以上'}],
        time: [{required: true, message: '预期完成时间是必填项'}]
    }

    toggleTag = (index) => {
        // 更新完state,在调用 getlist
        // this.setState({
        //     curTag: index
        // }, () => {
        //     this.getlist()
        // })
        flushSync(() => {
            this.setState({
                curTag: index
            });
        });
        this.getlist();
    }
    handleAdd = () => {
        this.setState({
            modelOpen: true,
        })
    }

    handleDelete = (id) => {
        removeTask({id}).then(res => {
            if (res.code === 0) {
                this.getlist();
                message.success('恭喜您，删除成功!');
            } else {
                message.warning('删除失败!');
            }
        })
    }

    handleUpdate = (id) => {
        completeTask({id}).then(res => {
            if (res.code === 0) {
                this.getlist();
                message.success('恭喜您，完成成功!');
            } else {
                message.warning('完成失败!');
            }
        })
    }

    // 行点击
    rowClick = (row) => {
        console.log('单行点击')
    }
    /* 对话框和表单处理 */
    closeModal = () => {
        this.setState({
            modelOpen: false,
        })
        this.formRef.resetFields();//清空内容
    }
    submit = () => {// 提交
        this.setState({confirmLoading: true});
        this.formRef.validateFields().then(data => {
            addTask(data).then(res => {
                if (res.code === 0) {
                    this.closeModal();
                    this.getlist()
                    this.setState({confirmLoading: false});
                    message.success('恭喜您，当前操作成功!');
                } else {
                    message.error('很遗憾，当前操作失败，请稍后再试!');
                }
            })
        })
    }

    getlist = () => {
        this.setState({
            tableLoading: true,
        })
        let params = {state: this.state.curTag}
        getTaskList(params).then(res => {
            if (res.code === 0) {
                let {list} = res
                this.setState({
                    listData: list,
                    tableLoading: false
                })
            }
        })
    }


    render() {
        return <div className="task-box">
            <div className="nav-title">
                <h2>TASK OA 任务关系系统 </h2>
                <Button type="primary" size="middle" onClick={this.handleAdd}>新增任务</Button>
            </div>
            <div className="tag-box">
                {['全部', '未完成', '已完成'].map((item, index) => {
                    return <Tag
                        color={this.state.curTag === index ? '#1677ff' : ''} key={index}
                        onClick={this.toggleTag.bind(this, index)}>{item}</Tag>
                })}
            </div>
            {/*表单*/}
            <Table
                rowKey={(record) => record.id}
                dataSource={this.state.listData}
                columns={this.state.columns}
                loading={this.state.tableLoading}
                onRow={row => {
                    return {
                        onClick: this.rowClick.bind(this, row)
                    }
                }}
            />
            {/*对话框*/}
            <Modal title='新增任务窗口'
                   open={this.state.modelOpen}
                   confirmLoading={this.state.confirmLoading}
                   keyboard={false} // esc关闭
                   maskClosable={false} // 点击蒙层关闭
                   okText="确认提交"
                   onCancel={this.closeModal}
                   onOk={this.submit}
            >
                <Form
                    ref={x => this.formRef = x}
                    layout='vertical'
                    initialValues={this.state.formData} // 设置初始值
                >
                    <Form.Item label="任务描述" name="task" validateTrigger="onBlur" rules={this.rules.task}>
                        <Input.TextArea rows={4}></Input.TextArea>
                    </Form.Item>
                    <Form.Item label="预期完成时间" name="time" rules={this.rules.time}>
                        <DatePicker/>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        console.log(11111) // 使用 pureComponent,数据值未更改不更新视图
    }

    componentDidMount() {
        this.getlist()
    }

}

export default Task


// 使用setState实现数据绑定
// <Input.TextArea rows={4} value={this.state.formData.task} onChange={(ev) => {
//     let target = ev.target,
//         text = target.value.trim();
//     this.setState({
//         // 'formData.task': text  // 这样无效
//         formData: {
//             ...this.state.formData,
//             task: text
//         }
//     })
// }}></Input.TextArea>